package main

import (
	"fmt"
	"net/http"
	"net/url"
	"io/ioutil"
	"strings"
	"net/http/cookiejar"
	"goquery"
)

/***************************************************************************************************
    Global Variables
***************************************************************************************************/
var gCurCookieJar *cookiejar.Jar
var gClient *http.Client

/***************************************************************************************************
    Functions
***************************************************************************************************/
//do init before all others
func initAll(){
	gCurCookieJar,_ = cookiejar.New(nil)
	gClient = &http.Client{
		Jar:gCurCookieJar,
	}
}

func DoSpider()  {
	preq, perr := http.NewRequest("GET", "http://acm.hdu.edu.cn/viewcode.php?rid=15086083", nil)
	if perr != nil {

	}
	resp, err := gClient.Do(preq)
	if  err != nil{
		fmt.Println("request error")
		return
	}
	defer resp.Body.Close()

	//data, _ := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(data))

	document,err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		fmt.Println("read document error")
		return
	}

	codeSel := document.Find("#usercode").Text()
	fmt.Println(codeSel)
}

func GetCookies()  {
	urlStr := "http://acm.hdu.edu.cn/userloginex.php?action=login"
	form := make(url.Values)
	form.Set("username", "yp0408100216")
	form.Set("userpass", "yp0408100216")
	form.Set("login", "Sign+In")

	bodyReader := ioutil.NopCloser(strings.NewReader(form.Encode()))

	req, err := http.NewRequest("POST", urlStr, bodyReader)
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0")
	req.Header.Set("Accepted", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := gClient.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
}

func main() {
	initAll()
	GetCookies()
	DoSpider()
}
